﻿namespace WebPacker
{
	using System;
	using System.Configuration;
	using System.Web;
	using System.Web.Routing;
	using WebPacker.Configuration;
	using WebPacker.Helpers;

	public static class RouteCollectionExtensions
	{
		public static void AddWebPackerRoute(this RouteCollection routes)
		{
			var section = ConfigurationManager.GetSection("web.packer") as WebPackerSection;

			if (section == null || section.Configuration == null)
			{
				throw new WebPackerException("Configuration isn't set.");
			}

			var router = section.Configuration.CreateRouter();

			AddWebPackerRoute(routes, router);
		}

		public static void AddWebPackerRoute(this RouteCollection routes, IPackRouter packRouter)
		{
			if (packRouter == null)
			{
				throw new ArgumentNullException("packRouter");
			}

			var url = packRouter.Url;

			if (url.StartsWith("~/"))
			{
				url = url.Substring(2);
			}
			else if (url.StartsWith(VirtualPathHelper.ApplicationVirtualPath))
			{
				url = url.Substring(VirtualPathHelper.ApplicationVirtualPath.Length);
			}

			if (url[0] != '/')
			{
				url = '/' + url;
			}

			routes.Add(new WebPackerRoute(url, new WebPackerRouteHandler()));
			WebPackerRouter.Instance = packRouter;
		}

		private class WebPackerRoute : RouteBase
		{
			private readonly string url;
			private readonly IRouteHandler routeHandler;

			public WebPackerRoute(string url, IRouteHandler routeHandler)
			{
				this.url = url;
				this.routeHandler = routeHandler;
			}

			public override RouteData GetRouteData(HttpContextBase httpContext)
			{
				var requestUrl = httpContext.Request.RawUrl;

				if (requestUrl.StartsWith(url))
				{
					return new RouteData(this, this.routeHandler);
				}

				return null;
			}

			public override VirtualPathData GetVirtualPath(RequestContext requestContext, RouteValueDictionary values)
			{
				return null;
			}
		}
	}
}